const express = require("express");
const multer = require("multer");
const path = require('path')
const router = express.Router();
const md5 = require("md5");
const upload = multer(); 
const usersModel = require("../../models/usersModel");
const jwt = require("jsonwebtoken");
const {secret} = require('../../config/config')

router.post("/registerUser", upload.any(),async (req, res) => {
  try {
    const { username, password } = req.body;
    console.log({ username, password });
    if (req.files.length > 0) {
      avatarData = req.files[0].buffer;
      avatarContentType = req.files[0].mimetype;
      encodedAvatar = Buffer.from(avatarData).toString('base64');
      imgSrc = `data:${avatarContentType};base64,${encodedAvatar}`;
    } else {
      const defaultAvatarPath = path.join(__dirname,'public/img/头像.png');
      avatarData = fs.readFileSync(defaultAvatarPath);
      avatarContentType = 'image/png';
      encodedAvatar = avatarData.toString('base64');
      imgSrc = `data:${avatarContentType};base64,${encodedAvatar}`;
    }
    await usersModel.create({ username, password: md5(password), avatar: imgSrc});

    res.json({
      code: 200,
      msg: "注册成功",
    });
  } catch (err) {
    if (err) {
      res.json({
        code: 500,
        msg: "注册失败",
        err,
      });
    }
  }
});

router.get("/logining", async (req, res) => {
  try {
    const { username, password } = req.query;
    const user = await usersModel.findOne({
      username,
      password: md5(password),
    }).select('-password -__v -_id');
    if (!user) {
      return res.json({
        code: "500",
        msg: "用户名或密码错误~~~",
        data: null,
      });
    }
    //创建当前用户的 token
    let token = jwt.sign(
      {
        username: user.username,
        _id: user._id,
      },
      secret,
      {
        expiresIn: 60 * 60 * 24 * 7,
      }
    );

    //响应 token
    res.json({
      code: "0000",
      msg: "登录成功",
      data:{
        token,
        user
      },
    });
  } catch (err) {
    res.json({
      code: 500,
      msg: "登录失败",
      err,
    });
  }
});
router.get('/getUser',async (req,res)=>{
try {
  console.log(req.query.username);
  const userMessage = await usersModel.findOne({username:req.query.username})
  res.json({
    code: "0000",
    msg: "查询成功",
    userMessage,
  })
} catch (error) {
  res.json({
    code: 500,
    msg: "查询失败",
    err,
  });
}
})
module.exports = router;
